package com.abel.bigwater.data.jnrq

import com.abel.bigwater.data.BcdString
import io.netty.buffer.ByteBuf


class WaterMeterData : JnrqReadData() {

    init {
        dataLen = 24
    }

    /**
     * 计算数据长度，针对解析和打包
     */
    override fun computeDataLen(): Int {
        return dataLen!!
    }

    /**
     * 从当前位置写入打包字节流
     */
    override fun fillBuffer(buf: ByteBuf) {
        assert(meterAddrStr?.size == 8)
        assert(sampleTimeStr?.size == 8)
        assert(readStatusStr?.size == 2)
        assert(reserved?.size == 2)

        val tmp = buf.alloc().buffer()
        tmp.writeBytes(meterAddrStr!!.hexArray)
        tmp.writeBytes(sampleTimeStr!!.hexArray)
        tmp.writeIntLE(waterDigitsInt!!.toInt())

        tmp.writeBytes(readStatusStr!!.hexArray)
        tmp.writeBytes(reserved!!.hexArray)

        buf.writeBytes(tmp)
    }

    /**
     * 解析字节流，从buf当前位置开始，并且消费其中的字节。
     */
    override fun parseBuffer(buf: ByteBuf) {
        val tmp = buf.duplicate()
        meterAddrStr = BcdString.create(tmp, 8)
        sampleTimeStr = BcdString.create(tmp, 8)
        waterDigitsInt = tmp.readUnsignedIntLE()
        readStatusStr = BcdString.create(tmp, 2)
        reserved = BcdString.create(tmp, 2)

        meterAddr
        sampleTime
        waterDigits

        buf.skipBytes(dataLen!!)
    }
}

/**
 * 状态位 2 XXH 00H BCD 吗 读表失败 XXH = 08H，
数据校验错 XXH = 04H
 */
enum class ReadStatusType {
    ReadFailure(0x08),
    ChecksumFailure(0x04),
    Success(0x00),
    UnknownStatus(0xFF.toByte());

    val status: Byte

    constructor(_status: Byte) {
        status = _status
    }

    companion object {
        fun findByStatus(code: Byte): ReadStatusType? {
            return ReadStatusType.values().find { it.status == code }
        }
    }
}